// pages/login/index.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		height: 64, //header高度
		top: 26, //标题图标距离顶部距离
		scrollH: 0, //滚动总高度
		barHeight: '32',
		opcity: 0,
		opcity_bg: 1,
		avatarUrl: '', //头像(全路径)
		half_avatarUrl: '', //头像(半路径,上传用)
		nickName: '', //昵称
		telephone: '', //手机号
		register: '', //是新注册还是重新登录
		back: true,
		//协议
		isAgree: false, //相关协议是否同意
		checkbox_animate: false, //震动效果
		focus: false
	},

	handleTouchInput() {
		wx.requirePrivacyAuthorize({
			success: res => {
				console.log('用户同意了隐私协议或无需用户同意隐私协议')
				// 用户同意隐私协议后给昵称input聚焦
				this.setData({
					focus: true
				})
			},
			fail: res => {
				console.log('用户拒绝了隐私协议')
			}
		})
	},
	handleGetNickname(e) {
		// 这里在工具上有bug，请使用手机扫码来验证
		console.log('nickname is', e.detail.value)
	},
	//协议勾选
	checks: function (e) {
		this.setData({
			isAgree: !!e.detail.value.length
		})
	},
	// //监听
	bind_set: function (e) { },
	//授权手机号(用手机号查询是否注册过、没注册过需要填写相关信息， 注册过直接登录)
	getPhoneNumber: function (e) {
		// var that = this;
		// if (e.detail.errMsg == "getPhoneNumber:ok") {
		// 	that.setData({
		// 		telephone: '13130599757', //替换授权过来的手机号
		// 		register: false, //如果注册过true/false
		// 		isAgree: true
		// 	});
		// }
		console.log(e);
        var that = this;
        if (e.detail.errMsg == "getPhoneNumber:ok") {
            var params = {}
            params.encryptedData = e.detail.encryptedData
            params.iv = e.detail.iv
            params.code = e.detail.code;

            getApp().util.request({
                url: 'user/get_mobile',
                data: params,
            }).then(function (res) {
                console.log(res)
                that.setData({
                    telephone: res.phone,
                    // isAgree: true
                })
            })
        }else{
            // wx.showToast({
            //   title: e.detail.errMsg,
            //   icon:'none'
            // });
        }
	},
	// //选择头像
	onChooseAvatar(e) {
		var that = this;
        const {
            avatarUrl
        } = e.detail;
        wx.getImageInfo({
            src: e.detail.avatarUrl,
            success(res) {
                console.log(res);
                if (res.width !== res.height) { //如果不是正方形 进行裁剪工作
                    //微信裁剪接口（2.26.0 开始支持）
                    wx.cropImage({
                        src: e.detail.avatarUrl, // 图片路径
                        cropScale: '1:1', // 裁剪比例
                        success(res) {
                            console.log(res)
                            getApp().util.uploadfile(res.tempFilePath, {}).then((res) => {
                                let src = res.data.fullurl
                                that.setData({
                                    avatarUrl: src,
                                });
                            })
                            // that.setData({
                            //     avatarUrl: res.tempFilePath
                            // })
                        },
                        fail: function (res) { },
                        complete: function (res) { }
                    })

                } else {
                    getApp().util.uploadfile(avatarUrl, {}).then((res) => {
                        let src = res.data.fullurl
                        that.setData({
                            avatarUrl: src,
                        });
                    })
                }
            },
            fail: function (res) { },
            complete: function (res) { }
        })
	},

	//提交登录
	formSubmit: function (e) {
		var that = this;
		let telephone = that.data.telephone; //手机号
		let avatarUrl = that.data.avatarUrl; //头像
		let nickName = that.data.nickName; //昵称
		let register = that.data.register; //是新注册还是登录
		let isAgree = that.data.isAgree; //相关协议是否同意
		console.log(avatarUrl)
		if (telephone == '') {
			wx.showToast({
				title: '请授权手机号码',
				icon: 'none',
				mask: false,
			});
			return false;
		}
		if (register == false) {
			if (telephone == '') {
				wx.showToast({
					title: '请授权手机号码',
					icon: 'none',
					mask: false,
				});
				return false;
			} else if (avatarUrl == '') {
				wx.showToast({
					title: '请上传头像',
					icon: 'none',
					mask: false,
				});
				return false;
			} else if (nickName == '') {
				wx.showToast({
					title: '请填写昵称',
					icon: 'none',
					mask: false,
				});
				return false;
			} else if (isAgree == false) {
				wx.showToast({
					title: '请阅读并同意相关协议条款',
					icon: 'none',
					duration: 1500
				});
				that.setData({
					checkbox_animate: true
				})
				setTimeout(() => {
					that.setData({
						checkbox_animate: false
					})
				}, 1500)
				return false
			}
		}
		if (isAgree == false) {
			wx.showToast({
				title: '请阅读并同意相关协议条款',
				icon: 'none',
				duration: 1500
			});
			that.setData({
				checkbox_animate: true
			})
			setTimeout(() => {
				that.setData({
					checkbox_animate: false
				})
			}, 1500)
			return false
		}
		that.setData({
			disabled: true
		})
		let params = {
			headimg: avatarUrl,
			nickname: nickName,
			mobile: telephone,
		};
		wx.login({
            //成功放回
            success: (res) => {
                let code = res.code
                params.code = code;
				getApp().util.request({
					url: 'user/wxlogin',
					data: params,
				}).then(function (res) {
					wx.setStorageSync('token',res.data)
					wx.switchTab({
					  url: '/pages/mydown/index',
					})
				}).catch(err=>{
					console.log('catch');
					console.log(err);
					that.setData({
						disabled: false
					})
				})
				that.setData({
					disabled: true
				})
			},
			error: (res) => {
                console.log(res);
                that.setData({
                    disabled: false,
                })
            }
		});
	},
	//返回上一页
	to_back: function (e) {
		// wx.navigateBack({
		//   delta: 1
		// })
	},
	//返回首页
	to_home: function (e) {
		// wx.switchTab({
		//   url: '/pages/home/index',
		// })
	},
	//跳转协议
	xieyi: function (e) {
		wx.navigateTo({
			url: '/pages/xieyi/index?type=1'
		})
	},
	//跳转政策
	zhengce: function (e) {
		wx.navigateTo({
			url: '/pages/xieyi/index?type=2'
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		var that = this;
		let obj = wx.getMenuButtonBoundingClientRect();
		this.setData({
			height: obj.top + obj.height + 8,
			top: obj.top + (obj.height - 32) / 2,
			barHeight: obj.height
		});
		var pages = getCurrentPages();
		var prevPage = pages[pages.length - 2]; //上一个页面
		if (prevPage) { //有上一页的 返回上一页
			that.setData({
				back: true
			})
		} else {
			that.setData({
				back: false
			})
		}
	},


	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})